import {
  Divider,
  Radio,
  Avatar,
  Card,
  Button,
  Table,
  Modal,
  Input,
  Form,
  Upload,
  message,
} from "antd";
import {
  SearchOutlined,
  UserOutlined,
  EditOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import type { ColumnsType } from "antd/es/table";
import React, { useState, useEffect } from "react";
// 引入请求接口
import {
  reqPageList,
  reqAddOrUpdateUser,
  reqDeleteUser,
  reqNewPgeList,
  reqRoles,
  reqDoAssign,
} from "@/api/user/index";
import "./index.css";
import { Checkbox } from "antd";
import type { CheckboxChangeEvent } from "antd/es/checkbox";
import type { CheckboxValueType } from "antd/es/checkbox/Group";
const CheckboxGroup = Checkbox.Group;

export default function Index() {
  // 为了操作表单 获取表单上所有数据 ,可以通过Form.useForm()函数,创建一个form实例
  const [form] = Form.useForm(); //固定
  const [form1] = Form.useForm();
  const [form3] = Form.useForm();
  // 分页相关的状态
  const [total, setTotal] = useState<number>(0);
  const [pageSize, setPageSize] = useState<number>(10);
  const [page, setPage] = useState<number>(1);
  // 用来存储列表数据
  const [pageList, setPageList] = useState([]);

  // 存储input输入框内的内容
  const [uaernameValue, setUaernameValue] = useState("");
  const [nickNameValue, setNickNameValue] = useState("");
  const [passwordValue, setPasswordValue] = useState("");
  // 定义接收当前一列的id
  const [userId, setUserId] = useState<any>();
  // 存储查询框内的内容
  const [inputValue, setInputValue] = useState("");

  const [isModaltf, setIsModaltf] = useState(false);

  //复选框
  //全部的数据
  const [plainOptions, setPlainOptions] = useState<any>([]);
  //已选中的数据
  const [checkedList, setCheckedList] = useState<any>();
  const [idItem, setIdItem] = useState<any>("");
  // 查询按钮的事件回调
  async function searchHandler() {
    let { search } = form1.getFieldsValue();
    // console.log(search);
    let result = await reqNewPgeList(page, pageSize, search);
    // console.log(result);
    setPageList(result.items);
    setTotal(result.total);
  }

  // table列表数据,包含俩按钮
  const columns: ColumnsType<any> = [
    {
      title: "序号",
      dataIndex: "name",
      render: (text, records, index) => {
        return index + 1;
      },
      align: "center",
      width: 120,
      key: "id",
    },
    {
      title: "用户名",
      dataIndex: "username",
      key: "username",
    },
    {
      title: "用户昵称",
      dataIndex: "nickName",
      key: "nickName",
    },
    {
      title: "角色列表",
      dataIndex: "roleName",
      key: "roleName",
    },
    {
      title: "创建时间",
      dataIndex: "gmtCreate",
      key: "gmtCreate",
    },
    {
      title: "更新时间",
      dataIndex: "gmtModified",
      key: "gmtModified",
    },
    {
      title: "操作",
      dataIndex: "made",
      fixed: "right",
      width: 200,
      render(value, records, index) {
        return (
          <div>
            <Button
              className="bt"
              type="primary"
              style={{}}
              icon={<UserOutlined />}
              onClick={async () => {
                //点击角色分配按钮
                setIsModaltf(true);
                form3.setFieldsValue({
                  yonghu: records.username,
                });

                let rs = await reqRoles(records.id);
                setPlainOptions(rs.allRolesList.map((item:any)=>({
                  label:item.roleName,
                  value:item.id
                })))       
                
                setCheckedList(rs.assignRoles.map((item:any)=>item.id))
                setIdItem(records.id)
              }}
            ></Button>
            <Button
              className="bt"
              type="primary"
              onClick={() => {
                updateHandle(records);
              }}
              style={{ background: "#E6A23C" }}
              icon={<EditOutlined />}
            ></Button>
            <Button
              className="bt"
              type="primary"
              onClick={() => {
                deleteHandle(records);
              }}
              style={{ background: "#f56c6c" }}
              icon={<DeleteOutlined />}
            ></Button>
          </div>
        );
      },
    },
  ];

  //    权限分配点击OK
  const qxfpOK = async () => {
    setIsModaltf(false);

    await reqDoAssign(idItem,checkedList.join(","))

  };
  //权限分配点击取消
  const qxfpqx = () => {
    setIsModaltf(false);
  };

  // 表格最后一列修改按钮的事件回调
  function updateHandle(records: any) {
    console.log(records);
    // 表格显示
    setIsModalOpen(true);
    form.setFieldsValue({
      username: records.username,
      nickName: records.nickName,
    });
    setUserId(records.id);
    getPageList(page, pageSize);
  }

  //  表格最后一列删除按钮的事件回调
  async function deleteHandle(records: any) {
    await reqDeleteUser(records.id);
    getPageList(page, pageSize);
  }

  useEffect(() => {
    getPageList(page, pageSize);
  }, []);
  // 获取列表数据
  async function getPageList(page: number, pageSize: number) {
    let result = await reqPageList(page, pageSize);
    // console.log(result);
    setPageList(result.items);
    setTotal(result.total);
  }
  // 列表可选框
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: any[]) => {
      console.log(
        `selectedRowKeys: ${selectedRowKeys}`,
        "selectedRows: ",
        selectedRows
      );
    },
    getCheckboxProps: (record: any) => ({
      // disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name,
    }),
  };

  // 弹框相关
  // 弹框显示隐藏标识符
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 点击添加按钮的事件回调
  const showModal = () => {
    setIsModalOpen(true);
    // 清空id
    setUserId("");
    form.resetFields();
  };

  // 弹框确定按钮的事件回调  (添加或修改)
  const handleOk = async () => {
    let data;
    // 获取表单上的输入框内容
    let { nickName, password, username, id } = form.getFieldsValue();
    // console.log(form.getFieldsValue());

    if (userId) {
      data = {
        username: username,
        nickName: nickName,
        password: password,
        id: userId,
      };
    } else {
      data = {
        username: username,
        nickName: nickName,
        password: password,
      };
    }
    // 对话框隐藏
    setIsModalOpen(false);
    // 发请求
    await reqAddOrUpdateUser(data);
    form.setFieldsValue({ username: "", nickName: "", password: "" });
    //  重新获取函数
    getPageList(page, pageSize);
  };
  // 弹框取消按钮的事件回调
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const onFinish = (values: any) => {
    console.log("Success:", values);
  };
  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };

  //复选框

  const onChange1 = (list: any) => {
    setCheckedList(list);
    console.log(list);
    // setIndeterminate(!!list.length && list.length < plainOptions.length);
    // setCheckAll(list.length === plainOptions.length);
  };

  return (
    <div>
      <Card>
        {/* 弹框 */}
        <>
          {/* <Button type="primary" onClick={showModal}>
        Open Modal
      </Button> */}
          <Modal
            title="添加用户"
            visible={isModalOpen}
            onOk={handleOk}
            onCancel={handleCancel}
          >
            <Form
              form={form}
              name="basic"
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 16 }}
              initialValues={{ remember: true }}
              onFinish={onFinish}
              onFinishFailed={onFinishFailed}
              autoComplete="off"
            >
              <Form.Item
                label="用户名"
                name="username"
                rules={[{ required: true, message: "请输入用户名" }]}
              >
                <Input value={uaernameValue} />
              </Form.Item>
              <Form.Item
                label="用户昵称"
                name="nickName"
                rules={[{ required: true, message: "请输入用户昵称" }]}
              >
                <Input value={nickNameValue} />
              </Form.Item>
              {userId ? (
                ""
              ) : (
                <Form.Item
                  label="用户密码"
                  name="password"
                  rules={[{ required: true, message: "请输入用户密码" }]}
                >
                  <Input value={passwordValue} />
                </Form.Item>
              )}
            </Form>
          </Modal>
        </>
        <Form form={form1} style={{ display: "flex" }}>
          <Form.Item name="search">
            <Input
              style={{ width: " 179px" }}
              className="inputName"
              type="text"
              placeholder="用户名"
            />
          </Form.Item>
          <Button
            type="primary"
            className="sure"
            onClick={searchHandler}
            icon={<SearchOutlined />}
          >
            查询
          </Button>
          <Button
            onClick={() => {
              form1.resetFields();
              getPageList(page, pageSize);
            }}
          >
            清空
          </Button>
        </Form>
        <div style={{ marginTop: "20px" }}>
          <Button type="primary" className="sure" onClick={showModal}>
            添加
          </Button>
          <Button type="primary" className="delete" style={{ border: "0" }}>
            批量删除
          </Button>
        </div>
        <Table
          rowKey="id"
          style={{ marginTop: "10px" }}
          rowSelection={{
            // type: checkbox,
            ...rowSelection,
          }}
          columns={columns}
          dataSource={pageList}
          scroll={{ x: 1300 }}
          pagination={{
            current: page, //current的值是几,对应的页码就会高亮
            total, //表示要分页的总数
            pageSize, //设置分页上,一页有多少条数据
            showSizeChanger: true, //是否展示 pageSize 切换器，当 total 大于 50 时默认为 true
            pageSizeOptions: [2, 5, 10], //指定每页可以显示多少条,和showSizeChanger配合使用
            showQuickJumper: true, //是否可以快速跳转至某页
            //用于显示数据总量和当前数据顺序,在分页器前面展示的内
            showTotal: function (total) {
              return `总共: ${total} 条`;
            },
            //	页码或 pageSize 改变的回调，参数是改变后的页码及每页条数
            onChange: function (page, pageSize) {
              // 异步
              setPageSize(pageSize);
              setPage(page);
              //  页面改变,重新获取页面数据
              //  调用获取表格数据的函数
              getPageList(page, pageSize);
            },
          }}
        />
        <Modal
          title="分配权限"
          visible={isModaltf}
          onOk={qxfpOK}
          onCancel={qxfpqx}
        >
          <Form form={form3}>
            <Form.Item label="用户名" name="yonghu">
              <Input disabled />
            </Form.Item>
            <Form.Item label="角色列表">
              <CheckboxGroup
                options={plainOptions}
                onChange={onChange1}
                value={checkedList}
              />
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </div>
  );
}
